import React, { useState, FunctionComponentElement, ReactNode } from 'react'
import classNames from 'classnames'
import { TabItemProps } from './tabItem'

export interface TabsProps {
  /**当前激活 tab 面板的 index，默认为0 */
  defaultIndex?: number
  /**可以扩展的 className */
  className?: string
  /**点击 Tab 触发的回调函数 */
  onSelect?: (selectedIndex: number) => void
  /**Tabs的样式，两种可选，默认为 line */
  type?: 'line' | 'card'
  children?: ReactNode
}

export const Tabs = ({
  defaultIndex = 0, // 默认激活的tab
  type = 'line',
  className,
  onSelect,
  children
}: TabsProps) => {
  const [activeIndex, setActiveIndex] = useState(defaultIndex)
  // 点击
  const handleClick = (_e: React.MouseEvent, index: number, disabled: boolean | undefined) => {
    if (!disabled) {
      setActiveIndex(index)
      onSelect?.(index)
    }
  }
  const renderNavLinks = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as FunctionComponentElement<TabItemProps>
      const { label, disabled } = childElement.props
      // 类名
      const classes = classNames('dog-tabs-nav-item', {
        'is-active': activeIndex === index,
        disabled: disabled
      })
      return (
        <li className={classes} key={`nav-item-${index}`} onClick={(e) => handleClick(e, index, disabled)}>
          {label}
        </li>
      )
    })
  }
  // tabs 对应的内容
  const renderContent = () => {
    return React.Children.map(children, (child, index) => {
      if (index === activeIndex) return child
    })
  }
  // 类名
  const navClass = classNames('dog-tabs-nav', {
    'nav-line': type === 'line',
    'nav-card': type === 'card'
  })
  return (
    <div className={`dog-tabs ${className}`}>
      <ul className={navClass}>{renderNavLinks()}</ul>
      <div className="dog-tabs-content">{renderContent()}</div>
    </div>
  )
}
export default Tabs
